﻿using Amiable.SDK;
using Amiable.SDK.Enum;
using Amiable.SDK.EventArgs;
using Amiable.SDK.Interface;
using AmiDraw.Lib.Factory;
using AmiDraw.Lib.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AmiDraw.Code
{
    public class GroupMsgEvent : IPluginEvent
    {
        public AmiableEventType EventType => AmiableEventType.Group;

        public void Process(AmiableEventArgs e)
        {
            var ee = e.AsMessageEventArgs();
            var msg = ee.RawMessage;
            var msginfo = MessagesLoader.GetMessageInfo(msg);


            if (msginfo != null)
            {
                var times = msginfo.Value.times;
                if (Util.UserDataUtil.GetLeftTime(ee.UserId) <= 0)
                {
                    var sb = new StringBuilder();
                    sb.AppendLine("赫尔并不想帮你抽卡，因为你没有剩余次数了");
                    sb.AppendLine("> 每天可以发送 抽卡3签到 来获取次数");
                    ee.SendMessage(sb.ToString());
                    return;
                }
                if (msginfo.Value.times != 0)
                {
                    ee.SendMessage("<赫尔·少女>正在祈祷中...");

                    List<DrawResult> drawResults = new List<DrawResult>();
                    for (int i = 0; i < msginfo.Value.times; i++)
                    {
                        drawResults.Add(DrawFactory.Draw(msginfo.Value.PackName, false, Lib.ResultQueryMode.Core));
                    }

                    var drawer = new DrawerFactory(msginfo.Value.PackName, drawResults, Lib.ResultQueryMode.Core);
                    using (var image = drawer.GenerateImage())
                    {
                        var tempPath = GetTempPath();
                        image.Save(tempPath);
                        ee.SendMessage(AppService.Instance.DefaultCodeProvider.Image(tempPath));
                    }
                    Util.UserDataUtil.AddLeftTime(ee.UserId, "default", -1);
                }
            }

        }

        public static string GetTempPath()
        {
            var dir = Path.Combine(AppContext.BaseDirectory, "Ami", "抽卡3", "temp");
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            return Path.Combine(dir, $"{Guid.NewGuid()}.jpg");
        }
    }
}

